# coding: utf8
from huaweicloudsdkcore.auth.credentials import GlobalCredentials
from huaweicloudsdkcdn.v1.region.cdn_region import CdnRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcdn.v1 import *
from ops.chatbot.utils.utils import get_kv_by_list


# 刷新cdn缓存
class CreateClient(object):
    def __init__(self):
        pass

    @staticmethod
    def create_client(
            cloud_type: str,
            access_key_id: str,
            access_key_secret: str,
            domain_id=None
    ):
        """
        使用AK&SK初始化账号Client
        @param cloud_type:
        @param access_key_id:
        @param access_key_secret:
        @param domain_id:
        @return: Client
        @throws Exception
        """
        if cloud_type == 'ali_cloud':
            config = open_api_models.Config(
                # 您的AccessKey ID,
                access_key_id=access_key_id,
                # 您的AccessKey Secret,
                access_key_secret=access_key_secret
            )
            # 访问的域名
            config.endpoint = 'dcdn.aliyuncs.com'
            client = dcdn20180115Client(config)
        elif cloud_type == 'hw_cloud':
            credentials = GlobalCredentials(access_key_id, access_key_secret, domain_id=domain_id)
            client = CdnClient.new_builder() \
                .with_credentials(credentials) \
                .with_region(CdnRegion.value_of("cn-north-1")) \
                .build()

        else:
            raise Exception('cdn只支持ali_cloud和hw_cloud两种云操作，请确认配置！')

        return client


class CdnOp(object):
    @staticmethod
    def create_domain(
            client,
            domain: str,
            ip_or_domain: str,
            business_type: str,
            service_area: str,
            origin_type: str

    ):
        """
        添加cdn域名
        """
        try:
            request = CreateDomainRequest()
            listSourcesDomain = [
                Sources(
                    ip_or_domain=ip_or_domain,
                    origin_type=origin_type,
                    active_standby=1
                )
            ]
            domainbody = DomainBody(
                domain_name=domain,
                business_type=business_type,
                sources=listSourcesDomain,
                service_area=service_area
            )
            request.body = CreateDomainRequestBody(
                domain=domainbody
            )

            response = client.create_domain(request)
            print(response)

            return {'code': 200, 'res': response}

        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
            return {'code': e.error_code, 'res': e.error_msg}

    @staticmethod
    def list_domains(client):
        """
        获取加速域名信息
        """
        try:
            request = ListDomainsRequest()
            response = client.list_domains(request)
            domains_list = response.domains
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
            domains_list = {}
        return domains_list

    @staticmethod
    def refresh_dcdn(
            client,
            object_path: str,
            object_type: str
    ):
        """
        刷新cdn缓存
        """
        try:
            request = CreateRefreshTasksRequest()
            listRefreshTaskRequestBodyUrlsRefreshTask = [
                object_path
            ]
            refreshTaskRefreshTaskRequestBody = RefreshTaskRequestBody(
                type=object_type,
                urls=listRefreshTaskRequestBodyUrlsRefreshTask
            )
            request.body = RefreshTaskRequest(
                refresh_task=refreshTaskRefreshTaskRequestBody
            )
            client.create_refresh_tasks(request)
            return {'code': 200, 'msg': '刷新成功'}
        except exceptions.ClientRequestException as e:
            print(e.error_code, e.error_msg)
            return {'code': e.error_code, 'msg': '刷新失败，原因{}'.format(e.error_msg)}

    @staticmethod
    def update_https_info(
            client,
            cert_name,
            domain_name,
    ):
        """
        更新域名的https配置
        """
        try:
            # 根据domain_name获取domain_id
            domains_list = get_kv_by_list(CdnOp.list_domains(client), 'domain_name', 'id')
            domain_id = domains_list.get(domain_name)

            request = UpdateHttpsInfoRequest()
            forceRedirectConfigHttps = ForceRedirect(
                switch=0
            )
            httpsbody = HttpInfoRequestBody(
                cert_name=cert_name,
                https_status=1,
                certificate_type=1,
                force_redirect_config=forceRedirectConfigHttps
            )
            request.body = HttpInfoRequest(
                https=httpsbody
            )
            request.domain_id = domain_id
            response = client.update_https_info(request)
            return {'code': 200, 'res': response}
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
            return {'code': e.error_code, 'res': e.error_msg}
